import React, {memo, useEffect, useState} from 'react'
import {
  mdiAlertCircle,
  mdiClose,
  mdiMedicalBag,
  mdiMinus,
  mdiPlus,
  mdiSilverwareForkKnife,
} from '@mdi/js'
import {Modal} from '../../../ui/modal/Modal'
import {ModalBody} from '../../../ui/modal/ModalBody'
import {Button} from '../../../ui/button/Button'
import {ModalFooter} from '../../../ui/modal/ModalFooter'
import {CONSTANTS} from '../../../../constants'
import ButtonIcon from '../../../ui/icon/ButtonIcon'
import {ModalHeader} from '../../../ui/modal/ModalHeader'
import {COLORS} from '../../../ui/color'
import {apiPost} from '../../../api'
import {CartDto} from '../../../../api/CartDto'
import {IMenuItem} from '../../../../api/IMenuItem'
import {IDishInfo} from '../../../../api/IDishInfo'
import {UserDto} from '../../../../api/UserDto'
import Icon from '../../../ui/icon/Icon'
import {LSKeys, LSMethods} from '../../../storage'

interface ProductModalProps {
  dish: IMenuItem
  user: UserDto
  cart: CartDto
  writeInCart: (newId: string, isRemove: boolean) => Promise<void>
  closeModal: () => void
}

const ProductModal: React.FC<ProductModalProps> = memo(
  ({dish, user, cart, writeInCart, closeModal}): React.ReactElement => {
    const [dishInfo, setDishInfo] = useState<IDishInfo | undefined>(undefined)

    const loadDishInfo = async (): Promise<void> => {
      let token: string
      if (user) {
        token = LSMethods.getStorageData(LSKeys.TOKEN)
      }
      const url = CONSTANTS.apiUrl + '/dish'
      const res = await apiPost(url, {id: dish.id, token: token}, {})
      const loadedDishInfo: IDishInfo = res.result
      setDishInfo({...loadedDishInfo})
    }

    useEffect(() => {
      loadDishInfo()
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [user])

    let consist: string | undefined
    if (dishInfo) {
      consist = ''
      for (let i = 0; i < (dishInfo?.consist || []).length; i++) {
        const item = dishInfo.consist[i]
        consist += `${item.name} ${item.amount} ${item.unit}${
          i !== dishInfo.consist.length - 1 ? ', ' : ''
        }`
      }
    }

    let newDishes = cart?.dishes
    let index: number | undefined
    let isIncludeInCart = false

    if (newDishes?.length > 0) {
      index = newDishes.findIndex((nd) => nd.id === dish.id)
      isIncludeInCart = index !== -1
    }

    return (
      <Modal isOpen={true} size={'lg'} onClose={closeModal}>
        <ModalHeader className={'d-flex justify-content-end'}>
          <ButtonIcon
            iconPath={mdiClose}
            title={''}
            color={COLORS.gray700}
            className={''}
            isHoverArea
            onClick={closeModal}
          />
        </ModalHeader>
        <ModalBody>
          <div className={'product-content'}>
            <div className={'d-flex flex-column align-items-center mb-x2'}>
              <img
                className={'product-content-img'}
                src={dish.img ? `${CONSTANTS.apiUrl}/image/${dish.id}` : '/buffet/img/bg_img.jpg'}
                alt={'Изображение блюда'}
              />
            </div>
            <p className={'product-content-name'}>{dish.dishname}</p>
            {consist && <p className={'product-content-description'}>Состав: {consist}</p>}

            {dishInfo?.is_allergy && (
              <p className={'mb-x2'}>
                <Icon
                  path={mdiAlertCircle}
                  color={COLORS.red}
                  className={'mb-x0 mr-x2'}
                  size={'20px'}
                />
                {dishInfo.is_allergy}
              </p>
            )}
            {dishInfo?.has_vitamine && (
              <p className={'mb-x2'}>
                <Icon
                  path={mdiMedicalBag}
                  color={COLORS.green}
                  size={'20px'}
                  className={'mb-x0 mr-x2'}
                />
                {dishInfo.has_vitamine}
              </p>
            )}
            {dishInfo?.diet_compatible && (
              <p className={'mb-x2'}>
                <Icon
                  path={mdiSilverwareForkKnife}
                  color={COLORS.gray700}
                  size={'20px'}
                  className={'mb-x0 mr-x2'}
                />
                {dishInfo.diet_compatible}
              </p>
            )}
            <div className={'pt-x2'}>
              <p className={'product-content-weight'}>
                Выход: {dish.amount} {dish.unit}
              </p>
              <p className={'product-content-price'}>
                Цена: <span className={'font-weight-medium'}>{dish.price} &#8381;</span>
              </p>
            </div>
          </div>
        </ModalBody>
        <ModalFooter className={'d-flex justify-content-end'}>
          <div className={'product-content-footer'}>
            {isIncludeInCart ? (
              <div className={'d-flex flex-row align-items-center min-h-40px'}>
                <ButtonIcon
                  iconPath={mdiMinus}
                  title={''}
                  className={'mr-x4'}
                  isHoverArea
                  onClick={async (): Promise<void> => {
                    await writeInCart(dish.id, true)
                  }}
                />
                <span>{newDishes[index].count}</span>
                <ButtonIcon
                  iconPath={mdiPlus}
                  title={''}
                  className={'ml-x4'}
                  isHoverArea
                  onClick={async (): Promise<void> => {
                    await writeInCart(dish.id, false)
                  }}
                />
              </div>
            ) : (
              <Button
                type={'button'}
                onClick={async (): Promise<void> => {
                  await writeInCart(dish.id, false)
                }}
                size={'md'}
                className={'mb-0'}>
                Купить
              </Button>
            )}
          </div>
        </ModalFooter>
      </Modal>
    )
  },
)

export {ProductModal}
